<template>
	<view class="category-container">
		<view class="sidebar">
			<view class="sidebar-item" v-for="(item, index) in categories" :key="index"
				:class="{ 'active': currentCategory === index }" @click="switchCategory(index)">
				<text>{{ item.name }}</text>
			</view>
		</view>

		<view class="content">
			<view class="category-title" v-if="categories.length > 0 && categories[currentCategory]">
				<text>{{ categories[currentCategory].name }}专区</text>
				<view class="title-more" @click="navigateToCategoryAll(categories[currentCategory].id)">
					查看全部 <text class="arrow">›</text>
				</view>
			</view>

			<view class="category-banner" v-if="categories.length > 0 && categories[currentCategory]">
				<image :src="categories[currentCategory].banner || '/static/default-banner.jpg'" mode="aspectFill">
				</image>
			</view>

			<view class="subcategory-list"
				v-if="categories.length > 0 && categories[currentCategory] && categories[currentCategory].subCategories">
				<view class="subcategory-item" v-for="(item, index) in categories[currentCategory].subCategories"
					:key="index" @click="navigateToSubcategory(item.id)">
					<image :src="item.image || '/static/default-category.jpg'" mode="aspectFill"></image>
					<text>{{ item.name }}</text>
				</view>
			</view>

			<view class="hot-products">
				<view class="section-title">热门商品</view>
				<view class="product-list">
					<view class="product-item" v-for="(item, index) in hotProducts" :key="index"
						@click="navigateToDetail(item.id)">
						<image :src="item.image || '/static/product-default.jpg'" mode="aspectFill"></image>
						<view class="product-info">
							<text class="product-name">{{ item.name }}</text>
							<text class="product-price">¥{{ item.price }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 添加自定义TabBar组件 -->
		<custom-tab-bar></custom-tab-bar>
	</view>
</template>

<script>
import CustomTabBar from '@/components/CustomTabBar.vue'

export default {
	components: {
		CustomTabBar
	},
	data() {
		return {
			currentCategory: 0,
			categories: [],
			hotProducts: [],
			// 备用数据，仅在API请求失败时使用
			fallbackCategories: [
				{
					id: 1,
					name: '狗狗',
					banner: '/static/dog-banner.jpg',
					subCategories: [
						{ id: 101, name: '狗粮', image: '/static/dog-food.jpg' },
						{ id: 102, name: '零食', image: '/static/dog-snack.jpg' },
						{ id: 103, name: '玩具', image: '/static/dog-toy.jpg' }
					]
				},
				{
					id: 2,
					name: '猫咪',
					banner: '/static/cat-banner.jpg',
					subCategories: [
						{ id: 201, name: '猫粮', image: '/static/cat-food.jpg' },
						{ id: 202, name: '零食', image: '/static/cat-snack.jpg' },
						{ id: 203, name: '玩具', image: '/static/cat-toy.jpg' }
					]
				}
			],
			fallbackProducts: [
				{ id: 1001, name: '皇家狗粮幼犬粮2kg', price: 199, image: '/static/product-1.jpg' },
				{ id: 1002, name: '猫咪逗笑激光笔', price: 29.9, image: '/static/product-2.jpg' },
				{ id: 1003, name: '宠物洗澡刷', price: 39, image: '/static/product-3.jpg' },
				{ id: 1004, name: '猫抓板组合', price: 79, image: '/static/product-4.jpg' }
			]
		}
	},
	onLoad(options) {
		this.loadCategories()
		this.loadHotProducts()

		// 如果有传入分类ID，则切换到对应分类
		if (options.id) {
			// 等待分类数据加载完成后切换
			setTimeout(() => {
				const index = this.categories.findIndex(item => item.id === parseInt(options.id));
				if (index !== -1) {
					this.currentCategory = index;
					// 加载该分类的详细信息
					this.loadCategoryDetail(this.categories[index].id);
				}
			}, 500)
		}
	},
	methods: {
		loadCategories() {
			this.$api.categoryApi.getList()
				.then(res => {
					console.log('分类数据:', res)
					if (res && res.code === 200 && res.data && res.data.length > 0) {
						this.categories = res.data
						// 加载默认选中分类的详情
						if (this.categories.length > 0) {
							this.loadCategoryDetail(this.categories[this.currentCategory].id);
						}
					} else {
						// 使用备用数据
						this.categories = this.fallbackCategories
						console.log('使用备用分类数据')
					}
				})
				.catch(err => {
					console.error('获取分类失败:', err)
					// 使用备用数据
					this.categories = this.fallbackCategories
					console.log('请求失败，使用备用分类数据')
				})
		},
		// 加载分类详情
		loadCategoryDetail(categoryId) {
			if (!categoryId) return;

			console.log('加载分类详情:', categoryId);
			// 调用分类详情API
			this.$api.categoryApi.getDetail(categoryId)
				.then(res => {
					console.log('分类详情数据:', res)
					if (res && res.code === 200 && res.data) {
						// 更新当前分类信息
						const index = this.categories.findIndex(item => item.id === categoryId);
						if (index !== -1) {
							// 合并分类详情数据
							this.categories[index] = { ...this.categories[index], ...res.data };
							console.log('更新后的分类信息:', this.categories[index]);
						}
					}
				})
				.catch(err => {
					console.error('获取分类详情失败:', err)
				});

			// 加载该分类下的热门商品
			this.loadCategoryProducts(categoryId);
		},
		// 加载分类商品
		loadCategoryProducts(categoryId) {
			this.$api.productApi.getList({
				categoryId: categoryId,
				size: 4,
				sortBy: 'sales',
				order: 'desc'
			})
				.then(res => {
					console.log('分类商品数据:', res)
					if (res && res.code === 200 && res.data && res.data.length > 0) {
						this.hotProducts = res.data
					} else {
						// 使用备用数据
						this.hotProducts = this.fallbackProducts
						console.log('使用备用商品数据')
					}
				})
				.catch(err => {
					console.error('获取分类商品失败:', err)
					// 使用备用数据
					this.hotProducts = this.fallbackProducts
					console.log('请求失败，使用备用商品数据')
				})
		},
		loadHotProducts() {
			this.$api.productApi.getList({
				size: 4, // 只获取4个热销商品
				sortBy: 'sales', // 按销量排序
				order: 'desc' // 降序
			})
				.then(res => {
					console.log('热门商品数据:', res)
					if (res && res.code === 200 && res.data && res.data.length > 0) {
						this.hotProducts = res.data
					} else {
						// 使用备用数据
						this.hotProducts = this.fallbackProducts
						console.log('使用备用商品数据')
					}
				})
				.catch(err => {
					console.error('获取热门商品失败:', err)
					// 使用备用数据
					this.hotProducts = this.fallbackProducts
					console.log('请求失败，使用备用商品数据')
				})
		},
		switchCategory(index) {
			if (this.currentCategory === index) return;

			this.currentCategory = index;
			// 选中分类后加载该分类的详情
			if (this.categories[index] && this.categories[index].id) {
				this.loadCategoryDetail(this.categories[index].id);
			}
		},
		// 查看分类全部
		navigateToCategoryAll(id) {
			if (!id) return;

			uni.navigateTo({
				url: '/pages/product/list?categoryId=' + id
			});
		},
		navigateToSubcategory(id) {
			uni.navigateTo({
				url: '/pages/product/list?categoryId=' + id
			});
		},
		navigateToDetail(id) {
			uni.navigateTo({
				url: '/pages/product/detail?id=' + id
			});
		}
	}
}
</script>

<style lang="scss">
.category-container {
	display: flex;
	height: 100vh;

	.sidebar {
		width: 180rpx;
		height: 100%;
		background-color: #f7f7f7;

		.sidebar-item {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			position: relative;
			color: #666;
			text-align: center;
			padding: 0 10rpx;

			&.active {
				background-color: #fff;
				font-weight: bold;
				color: #FF6600;

				&:before {
					content: '';
					position: absolute;
					left: 0;
					top: 30rpx;
					height: 40rpx;
					width: 6rpx;
					background-color: #FF6600;
				}
			}
		}
	}

	.content {
		flex: 1;
		padding: 20rpx;
		overflow-y: auto;

		.category-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15rpx;
			padding: 0 10rpx;

			text {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}

			.title-more {
				color: #666;
				font-size: 26rpx;
				display: flex;
				align-items: center;

				.arrow {
					margin-left: 5rpx;
					font-size: 30rpx;
				}
			}
		}

		.category-banner {
			width: 100%;
			height: 200rpx;
			border-radius: 10rpx;
			overflow: hidden;
			margin-bottom: 20rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.subcategory-list {
			display: flex;
			flex-wrap: wrap;
			background-color: #fff;
			border-radius: 10rpx;
			padding: 10rpx;

			.subcategory-item {
				width: 33.33%;
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 20rpx 0;

				image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					margin-bottom: 10rpx;
				}

				text {
					font-size: 24rpx;
					color: #333;
				}
			}
		}

		.hot-products {
			margin-top: 30rpx;

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.product-list {
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;

				.product-item {
					width: 48%;
					background-color: #fff;
					border-radius: 10rpx;
					overflow: hidden;
					margin-bottom: 20rpx;
					box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

					image {
						width: 100%;
						height: 200rpx;
					}

					.product-info {
						padding: 15rpx;

						.product-name {
							font-size: 28rpx;
							display: block;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}

						.product-price {
							font-size: 30rpx;
							color: #FF6600;
							font-weight: bold;
							margin-top: 10rpx;
						}
					}
				}
			}
		}
	}
}
</style>